package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.RequiredPermission;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是动态请求
        if (handler instanceof HandlerMethod) {
            //获取登录的信息，登录时存到session中的
            Employee emp = (Employee) request.getSession().getAttribute("USER_IN_SESSION");
            //判断是否超级管理员
            if (emp.isAdmin()) {
                //如果是就放行
                return true;
            }
            //不是管理员就获取访问的是否权限控制的页面
            HandlerMethod method = (HandlerMethod) handler;
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            if(methodAnnotation==null){
                //如果不需要访问限制的就直接放行
                return true;
            }
            //来到这步，说明当前方法需要权限控制

            String expression = methodAnnotation.expression();
            //TODO 登录的时候需要根据用户id查询出该用户拥有权限集合，放入到session
            List<Permission> permissionList =(List<Permission>)request.getSession().getAttribute("PERMISSION_IN_SESSION");
            //便利集合判断是否在集合中
            for(Permission p : permissionList){
                if(p.getExpression().equals(expression)){
                    //拥有权限直接放行
                    return true;
                }
            }
            //还需要判断是哪种请求 通过是否有贴@Responsebody注解判断是什么请求
            ResponseBody methodAnnotation1 = method.getMethodAnnotation(ResponseBody.class);
                //如果为空就是页面请求
            if(methodAnnotation1==null){
                //直接转发不经过视图解析器导致页面太丑了
                //request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response);
            response.sendRedirect("/nopermission");
            }else {
                response.setContentType("application/json;charset=utf-8");
                String responseData = JSON.toJSONString(new JsonResult(false, "不是VIP,请前往充值"));
                response.getWriter().write(responseData);
            }
            return false;
        }
        return true;
    }
}
